<template>
  <div>
    <div v-if="productList.length > 0" class="product-list">
      <ul>
        <li
          v-for="(item, index) in productList"
          :key="index"
          class="list"
          @click="loadProductDetail(item.id)"
        >
          <div class="list-left">
            <img class="img" :src="item.mainImage" alt="">
          </div>
          <div class="list-right">
            <div class="list-one overall">
              <div class="name">{{ item.childCategoryName }}</div>
              <div class="name">{{ item.repositoryName }}</div>
              <div class="name">{{ item.price | moneyFormat }}元/{{ item.unit }}</div>
              <div class="name">
                <span v-if="!item.feeMoney" class="transport-total">运费总价：计算中</span>
                <span v-else class="transport-total">运费总价：￥{{ item.feeMoney |moneyFormat }}</span>
              </div>
            </div>
            <div class="list-two overall">
              <div class="name store-name" @click.stop="toStore(item.sellerId)"><i class="iconfont icon-shop shop" />{{ item.sellerName }}</div>
              <div class="name">
                <span v-if="!item.distance">运输里程：计算中</span>
                <span v-else>运输里程：{{ item.distance }} km</span>
              </div>
              <div class="num name">采购数量：{{ condition.buyNum }} {{ item.unit }}</div>
              <div class="name">商品总价：￥{{ spuTotalPrice(item.price,condition.buyNum) | moneyFormat }}</div>
              <div class="name">
                <span v-if="!item.feeMoney">总计：计算中</span>
                <span v-else>总计：{{ spuAllPrice(item.feeMoney,spuTotalPrice(item.price,condition.buyNum)) | moneyFormat }}</span>
              </div>
            </div>
            <div class="list-three">
              <i class="iconfont icon-phone-num relation" @click.stop="getPhone(item)" />
            </div>
          </div>
        </li>
      </ul>
    </div>
    <div v-if="productList.length === 0">
      当前条件无商品
    </div>
    <div class="page">
      <el-pagination
        v-show="condition.pageIndex && pageParams.total > 0"
        :total="pageParams.total"
        :current-page.sync="condition.pageIndex"
        :page-size.sync="pageParams.size"
        background
        layout="prev, pager, next"
        @current-change="changePage"
      />
    </div>
    <el-dialog
      title="联系方式"
      :visible.sync="phoneDialog.open"
      width="30%"
      :before-close="handleClose"
    >
      <div class="relation-box">
        <div><span>联系人：</span><span>{{ phoneDialog.data.salesman }}</span></div>
        <div><span>联系电话：</span><span>{{ phoneDialog.data.contactPhone }}</span></div>
        <div v-for="(item,index) in phoneDialog.data.emergoyPhone" :key="index">
          <span :class="index !== 0?'hidden-title':''">办公电话：</span><span>{{ item }}</span>
        </div>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { Decimal } from 'decimal.js'
import { recordContact } from '@/api/record/index'
import { loadSpu, loadFee } from '@/api/search/newConseQuence'
import { loadPhone } from '@/util/spuContantWay'
import { toProductDetail, toShopList } from '@/js/product'
export default {
  name: 'SearchProductList',
  props: {
    condition: {
      type: Object,
      required: true
    },
    brandList: {
      type: Object,
      required: true
    },
    showSortAll: {
      type: Boolean,
      required: true

    }
  },
  data() {
    return {
      productList: [],
      pageParams: {
        size: 40, // 每页大小
        total: 0 // 总数据量
      },
      loadFee: {
        loadFeeFunction: [], // 延迟执行代码对象
        loadFeeFlag: 0 // 加载运费统计

      },
      phoneDialog: {
        open: false,
        data: {}
      }
    }
  },
  watch: {
    productList: {
      handler: function(newVal) {
        const _this = this
        newVal.forEach((temp, i) => {
          _this.loadFee.loadFeeFunction.push(setTimeout(() => {
            const buyNum = this.condition.buyNum < parseInt(temp.minBuyNum) ? parseInt(temp.minBuyNum) : this.condition.buyNum
            const end = `${this.condition.address.latitude},${this.condition.address.longitude}`
            const spuId = temp.spuId
            const reposityId = temp.repositoryId
            const _this = this
            loadFee({ end, spuId, reposityId, buyNum }).then(res => {
              _this.loadFee.loadFeeFlag++
              _this.productList[i].distance = res.data.distance
              _this.productList[i].feeMoney = res.data.fee
              if (_this.loadFee.loadFeeFlag === _this.productList.length) {
                this.$emit('update:showSortAll', true)
              }
            })
          }, (i + 1) * 1000 - 600))
        })
      }
    }
  },
  beforeDestroy() {
    this.resetCaculateFee()
  },
  created() {
    this.listSpu()
    this.$emit('recordCondition', false)
  },
  methods: {
    // 获取联系方式
    getPhone(item) {
      const spuId = item.spuId
      const id = item.id
      // 直接匿名函数搞定
      loadPhone(spuId, (data) => {
        this.phoneDialog.data = data
        if (data.emergoyPhone) {
          this.phoneDialog.data.emergoyPhone = data.emergoyPhone.split(',')
        }
        this.phoneDialog.open = true
      }, onlyAccount => {
        const item = this.productList.filter(i => i.spuId === spuId && i.id === id)[0]
        recordContact({
          id,
          productName: item.childCategoryName,
          repositoryName: item.repositoryName,
          sellerName: item.sellerName,
          spuId,
          onlyAccount
        })
      })
    },
    // 页码变化
    changePage() {
      this.resetCaculateFee()
      this.$emit('refreshCondition')
    },
    // 计算商品总价
    spuTotalPrice(price, num) {
      return new Decimal(price).mul(new Decimal(num))
    },
    // 计算商品总计
    spuAllPrice(feeMoney, spuTotalPrice) {
      return new Decimal(feeMoney).add(new Decimal(spuTotalPrice))
    },
    // 进入店铺页
    toStore(sellerId) {
      // console.log('进入店铺页')
      toShopList(this, sellerId)
    },
    // 进入商品详情页
    loadProductDetail(spuRepoId) {
      const end = this.$store.getters.searchSite
      console.log(this.$store.getters.searchSite, '搜索页地址')
      console.log(this.$store.getters.searchResult, '1117')
      console.log(end, '777777')
      // SEARCH_SITEthis.$store.getters.searchResult
      toProductDetail(this, spuRepoId, end)
    },
    // 加载列表
    listSpu() {
      this.resetCaculateFee()
      if (!this.condition.pageIndex) {
        this.condition.pageIndex = 1
      }
      const childCategoryId = this.condition.childCategory.id
      const mainCategoryId = this.condition.mainCategory.id
      const proaId = this.condition.proaId
      const probId = this.condition.probId
      const procId = this.condition.procId
      const prodId = this.condition.prodId
      const proeId = this.condition.proeId
      const lng = this.condition.address.longitude
      const lat = this.condition.address.latitude
      const searchRange = this.condition.searchRange
      const sortType = this.condition.sortType
      const sortMethod = this.condition.sortMethod
      const brandId = this.brandList.brandId
      const buyNum = this.condition.buyNum
      const skuNumFlag = this.condition.skuNumFlag
      loadSpu(this.pageParams.size, this.condition.pageIndex, { childCategoryId, mainCategoryId, proaId, probId, procId, prodId, proeId, lng, lat, searchRange, sortType, sortMethod, brandId, buyNum, skuNumFlag }).then(res => {
        if (res.code === 0) {
          this.pageParams.total = res.data.total
          res.data.records.forEach(e => {
            e.distance = 0
            e.feeMoney = 0
          })
          this.productList = res.data.records
        }
      })
    },
    // 总计最优排序
    sortAll() {
      const _this = this
      this.productList.sort((a, b) => {
        return new Decimal(a.feeMoney).add(_this.spuTotalPrice(a.price, _this.condition.buyNum)).sub(new Decimal(b.feeMoney).add(_this.spuTotalPrice(b.price, _this.condition.buyNum))).toNumber()
      })
    },
    // 重置运费计算=
    resetCaculateFee() {
      this.loadFee.loadFeeFunction.forEach(e => clearTimeout(e))
      this.loadFee.loadFeeFlag = 0
    },
    handleClose() {
      this.phoneDialog.open = false
    }
  }
}
</script>

<style lang='scss' scoped >
  .product-list {
    background: #ffffff;
    margin-bottom: 40px;
    .list {
      display: flex;
      padding: 14px 0 20px 20px;
      border-bottom: 1px solid #e5e5e5;
      .list-left {
        display: flex;
        .img {
          width: 80px;
          height: 80px;
          margin-right: 44px;
        }
        .left-detail {
          line-height: 26px;
          .color {
            color: #c7c7cc;
            font-size: 10px;
          }
        }
      }
      .list-right {
        display: flex;
        flex-direction: column;
        line-height: 24px;
        .overall {
          display: flex;
          span {
            color: #ff3b30;
          }
        }
        .list-one {
          .name{
            width: 200px;
          }
        }
        .list-two {
          .store-name{
            cursor: pointer;
            .shop{
              margin-right: 4px;
            }
          }
          .num {
            padding-right: 28px;
          }

          .name{
            width: 200px;
          }
        }
        .list-three {
          cursor: pointer;
          width: 32px;
          height: 32px;
        }
      }
    }
    .list:last-child {
      border-bottom: none;
    }
  }
  .page {
    display: flex;
    justify-content: center;
    margin-bottom: 60px;
  }
  .relation-box {
    display: flex;
    justify-content: center;
    flex-direction: column;
    font-size: 14px;
    color: #6b6b6b;
    padding-left: 20px;
    line-height: 34px;
    .hidden-title{
      visibility: hidden;
    }
  }
  /deep/ .search-box {
    .el-form-item__label {
      width: 106px !important;
    }
  }
  /deep/.site-input {
    .el-input {
      width: 230px;
    }
  }
  /deep/ .range {
    .el-input {
      width: 74px;
    }
  }
  /deep/ .num {
    .el-input-number {
      width: 134px;
    }
  }
  /deep/ .range-box {
    .el-input {
      width: 126px;
    }
  }
  /deep/ .purchase {
    .el-input {
      width: 126px;
    }
  }
  /deep/ .dialog {
    .el-dialog__footer {
      display: flex;
      justify-content: center;
      .el-button--primary {
        width: 110px;
        height: 37px;
        background: #ff3b30;
        color: #ffffff;
        border: none;
      }
      .el-button--default {
        width: 110px;
        height: 37px;
        border: 1px solid #e5e5e5;
        background: #e5e5e5;
        color: #6b6b6b;
      }
    }
  }
  /deep/ .amending {
    display: flex;
    justify-content: center;
    padding-right: 91px;
    .el-input {
      width: 236px;
    }
  }
</style>
